package com.zenithmind.exam.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.Result;
import com.zenithmind.exam.pojo.entity.WrongQuestion;
import com.zenithmind.exam.pojo.vo.QuestionVO;
import com.zenithmind.exam.service.WrongQuestionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.NotBlank;
import java.util.List;

/**
 * 错题本控制器
 * 
 * @author ZenithMind
 * @since 2024-07-01
 */
@Slf4j
@RestController
@RequestMapping("/api/exam/wrong-question")
@RequiredArgsConstructor
@Validated
@Tag(name = "错题本管理", description = "错题本的相关操作")
public class WrongQuestionController {

    private final WrongQuestionService wrongQuestionService;

    @PostMapping("/{questionId}")
    @Operation(summary = "添加错题", description = "添加题目到错题本")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> addWrongQuestion(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId,
            @Parameter(description = "考试记录ID") @RequestParam(required = false) String examRecordId) {
        String userId = UserContext.getUserId();
        boolean result = wrongQuestionService.addWrongQuestion(userId, questionId, examRecordId);
        return Result.success(result);
    }

    @PutMapping("/{questionId}/mastered")
    @Operation(summary = "标记为已掌握", description = "标记题目为已掌握")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> markAsMastered(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId) {
        String userId = UserContext.getUserId();
        boolean result = wrongQuestionService.markAsMastered(userId, questionId);
        return Result.success(result);
    }

    @PutMapping("/{questionId}/not-mastered")
    @Operation(summary = "标记为未掌握", description = "标记题目为未掌握")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> markAsNotMastered(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId) {
        String userId = UserContext.getUserId();
        boolean result = wrongQuestionService.markAsNotMastered(userId, questionId);
        return Result.success(result);
    }

    @GetMapping("/my-wrong-questions")
    @Operation(summary = "获取我的错题", description = "获取当前用户的错题列表")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<QuestionVO>> getMyWrongQuestions() {
        String userId = UserContext.getUserId();
        List<QuestionVO> questions = wrongQuestionService.getUserWrongQuestions(userId);
        return Result.success(questions);
    }

    @GetMapping("/my-mastered-questions")
    @Operation(summary = "获取我的已掌握题目", description = "获取当前用户已掌握的错题列表")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<QuestionVO>> getMyMasteredQuestions() {
        String userId = UserContext.getUserId();
        List<QuestionVO> questions = wrongQuestionService.getUserMasteredQuestions(userId);
        return Result.success(questions);
    }

    @GetMapping("/my-wrong-questions/page")
    @Operation(summary = "分页查询我的错题", description = "分页查询当前用户的错题")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<IPage<QuestionVO>> getMyWrongQuestionPage(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "是否已掌握") @RequestParam(defaultValue = "0") Integer isMastered) {
        
        String userId = UserContext.getUserId();
        Page<WrongQuestion> page = new Page<>(pageNum, pageSize);
        IPage<QuestionVO> result = wrongQuestionService.getUserWrongQuestionPage(page, userId, isMastered);
        return Result.success(result);
    }

    @GetMapping("/my-wrong-questions/count")
    @Operation(summary = "统计我的错题数量", description = "统计当前用户的错题数量")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Integer> getMyWrongQuestionCount(
            @Parameter(description = "是否已掌握") @RequestParam(defaultValue = "0") Integer isMastered) {
        String userId = UserContext.getUserId();
        Integer count = wrongQuestionService.countUserWrongQuestions(userId, isMastered);
        return Result.success(count);
    }

    @GetMapping("/my-frequent-wrong")
    @Operation(summary = "获取我的高频错题", description = "获取当前用户的高频错题")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<QuestionVO>> getMyFrequentWrongQuestions(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = UserContext.getUserId();
        List<QuestionVO> questions = wrongQuestionService.getFrequentWrongQuestions(userId, limit);
        return Result.success(questions);
    }

    @GetMapping("/my-recent-wrong")
    @Operation(summary = "获取我的最近错题", description = "获取当前用户最近的错题")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<QuestionVO>> getMyRecentWrongQuestions(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = UserContext.getUserId();
        List<QuestionVO> questions = wrongQuestionService.getRecentWrongQuestions(userId, limit);
        return Result.success(questions);
    }

    @DeleteMapping("/my-wrong-questions/clear")
    @Operation(summary = "清空我的错题本", description = "清空当前用户的错题本")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> clearMyWrongQuestions() {
        String userId = UserContext.getUserId();
        boolean result = wrongQuestionService.clearUserWrongQuestions(userId);
        return Result.success(result);
    }

    @PostMapping("/batch-mastered")
    @Operation(summary = "批量标记为已掌握", description = "批量标记题目为已掌握")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> batchMarkAsMastered(
            @Parameter(description = "题目ID列表") @RequestBody List<String> questionIds) {
        String userId = UserContext.getUserId();
        boolean result = wrongQuestionService.batchMarkAsMastered(userId, questionIds);
        return Result.success(result);
    }

    @GetMapping("/my-wrong-questions/question-ids")
    @Operation(summary = "获取我的错题ID", description = "获取当前用户错题的题目ID列表")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<String>> getMyWrongQuestionIds(
            @Parameter(description = "是否已掌握") @RequestParam(defaultValue = "0") Integer isMastered) {
        String userId = UserContext.getUserId();
        List<String> questionIds = wrongQuestionService.getUserWrongQuestionIds(userId, isMastered);
        return Result.success(questionIds);
    }

    @GetMapping("/question/{questionId}/wrong-count")
    @Operation(summary = "获取题目错误次数", description = "获取指定题目的错误次数")
    public Result<Integer> getQuestionWrongCount(
            @Parameter(description = "题目ID") @PathVariable @NotBlank String questionId) {
        Integer count = wrongQuestionService.getQuestionWrongCount(questionId);
        return Result.success(count);
    }

    @GetMapping("/practice")
    @Operation(summary = "生成错题练习", description = "生成错题练习题目")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<QuestionVO>> generateWrongQuestionPractice(
            @Parameter(description = "题目数量") @RequestParam(defaultValue = "10") Integer count) {
        String userId = UserContext.getUserId();
        List<QuestionVO> questions = wrongQuestionService.generateWrongQuestionPractice(userId, count);
        return Result.success(questions);
    }

    @GetMapping("/my-statistics")
    @Operation(summary = "获取我的错题统计", description = "获取当前用户的错题统计信息")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER') or hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<WrongQuestion> getMyWrongQuestionStatistics() {
        String userId = UserContext.getUserId();
        WrongQuestion statistics = wrongQuestionService.getWrongQuestionStatistics(userId);
        return Result.success(statistics);
    }
}
